<route lang="yaml">
  title: 时间工具
  meta:
    enabled: true
</route>

<script setup lang="ts">
import { useClipboard } from '@vueuse/core'
import { ref } from 'vue'
import { toast } from 'vue-sonner'

const { text, copy, copied } = useClipboard()

const timestamp = ref('')
const datetime = ref('')
const timezone = ref('Asia/Shanghai')

const isMillisecond = ref(false)

// 时间戳转日期时间
function timestampToDatetime() {
  if (!timestamp.value) {
    return ''
  }
  try {
    const timeValue = isMillisecond.value ? Number(timestamp.value) : Number(timestamp.value) * 1000
    return new Date(timeValue).toLocaleString('zh-CN', { timeZone: timezone.value })
  }
  catch (e) {
    return `无效的时间戳${(e as Error).message}`
  }
}

// 日期时间转时间戳
function datetimeToTimestamp() {
  if (!datetime.value) {
    return ''
  }
  try {
    const timestamp = new Date(datetime.value).getTime()
    return isMillisecond.value ? timestamp.toString() : Math.floor(timestamp / 1000).toString()
  }
  catch (e) {
    return `无效的日期时间${(e as Error).message}`
  }
}

// 当前时间戳
const currentTimestamp = ref(Math.floor(Date.now() / 1000).toString())
// 当前时间戳(带毫秒)
const currentTimestampWithMs = ref(Date.now().toString())
// 当前日期时间
const currentDatetime = ref(new Date().toLocaleString('zh-CN', { timeZone: timezone.value }))

// 定时更新当前时间
let timer: number
onMounted(() => {
  timer = window.setInterval(() => {
    const now = Date.now()
    const newTimestamp = Math.floor(now / 1000).toString()
    const newTimestampWithMs = now.toString()
    const newDatetime = new Date(now).toLocaleString('zh-CN', { timeZone: timezone.value })
    currentTimestamp.value = newTimestamp
    currentTimestampWithMs.value = newTimestampWithMs
    currentDatetime.value = newDatetime
  }, 1000)
})

onUnmounted(() => {
  clearInterval(timer)
})

watch(copied, (val) => {
  val && toast.success(`复制成功：${text.value}`)
})
</script>

<template>
  <div>
    <FaPageHeader title="时间工具" description="时间戳与日期时间相互转换">
      <FaButton variant="outline" @click="copy(currentTimestamp)">
        <FaIcon name="i-ep:link" />
        复制当前时间戳
      </FaButton>
    </FaPageHeader>

    <FaPageMain title="当前时间">
      <div class="space-y-4">
        <ElInput
          :model-value="currentTimestamp"
          placeholder="当前时间戳(秒)"
          readonly
        />
        <ElInput
          :model-value="currentTimestampWithMs"
          placeholder="当前时间戳(毫秒)"
          readonly
        />
        <ElInput
          :model-value="currentDatetime"
          placeholder="当前日期时间"
          readonly
        />
        <div class="space-x-2">
          <FaButton @click="copy(currentTimestamp)">
            复制秒级时间戳
          </FaButton>
          <FaButton @click="copy(currentTimestampWithMs)">
            复制毫秒时间戳
          </FaButton>
          <FaButton @click="copy(currentDatetime)">
            复制日期时间
          </FaButton>
        </div>
      </div>
    </FaPageMain>

    <FaPageMain title="时间戳转日期时间">
      <div class="space-y-4">
        <ElInput
          v-model="timestamp"
          :placeholder="isMillisecond ? '输入时间戳（毫秒）' : '输入时间戳（秒）'"
          clearable
        />
        <ElSwitch
          v-model="isMillisecond"
          active-text="毫秒级"
          inactive-text="秒级"
        />
        <ElInput
          :model-value="timestampToDatetime()"
          placeholder="转换结果"
          readonly
        />
        <div class="space-x-2">
          <FaButton @click="copy(timestampToDatetime())">
            复制结果
          </FaButton>
          <FaButton @click="timestamp = isMillisecond ? currentTimestampWithMs : currentTimestamp">
            使用当前时间戳
          </FaButton>
        </div>
      </div>
    </FaPageMain>

    <FaPageMain title="日期时间转时间戳">
      <div class="space-y-4">
        <ElInput
          v-model="datetime"
          placeholder="输入日期时间（如：2023-01-01 12:00:00）"
          clearable
        />
        <ElSwitch
          v-model="isMillisecond"
          active-text="毫秒级"
          inactive-text="秒级"
        />
        <ElInput
          :model-value="datetimeToTimestamp()"
          placeholder="转换结果"
          readonly
        />
        <div class="space-x-2">
          <FaButton @click="copy(datetimeToTimestamp())">
            复制结果
          </FaButton>
          <FaButton @click="datetime = currentDatetime">
            使用当前时间
          </FaButton>
        </div>
      </div>
    </FaPageMain>
  </div>
</template>

<style scoped>
.space-y-4 > * + * {
  margin-top: 1rem;
}
</style>
